import logging
import os
from logging.handlers import RotatingFileHandler


# 注册日志组件
def register_logger(app):

    # 取得日志级别
    def log_level(app):
        if app.config['LOG_LEVEL'] == 'DEBUG':
            return logging.DEBUG
        elif app.config['LOG_LEVEL'] == 'INFO':
            return logging.INFO
        elif app.config['LOG_LEVEL'] == 'WARN':
            return logging.WARN
        elif app.config['LOG_LEVEL'] == 'ERROR':
            return logging.ERROR
        elif app.config['LOG_LEVEL'] == 'FATAL':
            return logging.FATAL
        else:
            return logging.NOTSET

    # Formatter
    formatter = logging.Formatter(app.config['LOG_FORMATTER'])
    if not os.path.exists(app.config['LOG_PATH']):
        os.makedirs(app.config['LOG_PATH'])
    # FileHandler Info
    file_handle = RotatingFileHandler(filename=app.config['LOG_PATH_INFO'])
    file_handle.setFormatter(formatter)
    file_handle.setLevel(log_level(app))
    app.logger.addHandler(file_handle)


